import React from 'react';
import {
    StyleSheet,
    FlatList,
    View,
    Text,
    ActivityIndicator,
    Image,
} from 'react-native';

import CommunitySortView from "../sort/CommunitySortView"
import CommunityHeaderCell from "../cell/CommunityHeaderCell"
import CommunityContentCell from "../cell/CommunityContentCell"
import CommunityTitleCell from "../cell/CommunityTitleCell"
import CommunityMediaGatherCell from "../cell/CommunityMediaGatherCell"
import CommunityMediaCell from "../cell/CommunityMediaCell"
import CommunityToolCell from "../cell/CommunityToolCell"

import { videos_commentAction } from '../../utils'
import { videos_shareAction } from '../../utils'
import { videos_moreAction } from '../../utils'
import { videos_clickCellAction } from '../../utils'
import { videos_clickImgAction } from '../../utils'

const keywords = ["回合战斗", "官方视频", "武侯玄机", "黄子韬的夏日奇遇"]

const dataSource = [{
    "id": "1",
    "title": "《黄子韬的夏日奇遇》武馆篇首发上...",
    "content": "连续两周，《神武3》暑期合作系列片《黄子韬的夏日奇遇》音乐篇、园林篇相继上线，今日（7月12日），本系列的最终章--武馆...",
    "needRichText": 1,
    "img": [{ "url": "https://image.duoyi.com/com/322/pic/086467178089444d818a3d76a56538f0.jpg", "width": 680, "height": 382 }],
    "gameName": "神武4手游",
    "time": "2019-07-17",
    "gameIcon": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1582011742167&di=a1fbe78b2b60f0afe89cb66b7175164b&imgtype=jpg&src=http%3A%2F%2Fimg0.imgtn.bdimg.com%2Fit%2Fu%3D3460423160%2C2339690649%26fm%3D214%26gp%3D0.jpg",
    "comment": "4",
    "thumbup": "7"
},
{
    "id": "2",
    "title": "黄子韬的夏日奇遇--园林篇",
    "content": "巨石、黑松、瀑布、锦鲤......在最新一集《黄子韬的夏日奇遇》中，刚刚在《神武3》手游“装扮秀”争冠失利的黄子韬来到罗红摄影艺...",
    "needRichText": 1,
    "img": [],
    "gameName": "神武4手游",
    "time": "2019-07-08",
    "gameIcon": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1582011742167&di=a1fbe78b2b60f0afe89cb66b7175164b&imgtype=jpg&src=http%3A%2F%2Fimg0.imgtn.bdimg.com%2Fit%2Fu%3D3460423160%2C2339690649%26fm%3D214%26gp%3D0.jpg",
    "comment": "0",
    "thumbup": "6"
},
{
    "id": "3",
    "title": "《黄子韬的夏日奇遇》园林篇，邀你",
    "content": "今日，《神武3》暑期合作系列片《黄子韬的夏日奇遇》第二季“园林篇”正式上线，第一集“音乐篇”全网同步解锁（传送门：",
    "needRichText": 0,
    "img": [{ "url": "https://image.duoyi.com/com/322/pic/3b166f20d0a940acb2b0fdb9e1d43f83.jpg", "width": 567, "height": 384 },
    { "url": "https://image.duoyi.com/com/322/pic/4ed2101aba424a55bc4aba4595719e37.jpg", "width": 567, "height": 384 }],
    "gameName": "神武4手游",
    "time": "2019-07-05",
    "gameIcon": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1582011742167&di=a1fbe78b2b60f0afe89cb66b7175164b&imgtype=jpg&src=http%3A%2F%2Fimg0.imgtn.bdimg.com%2Fit%2Fu%3D3460423160%2C2339690649%26fm%3D214%26gp%3D0.jpg",
    "comment": "0",
    "thumbup": "11"
},
{
    "id": "4",
    "title": "《黄子韬的夏日奇遇》音乐篇精彩花...",
    "content": "今日（6月28日），蓄势已久的《黄子韬的夏日奇遇》系列片之音乐篇首发！除此之外，令人期待的《神武3》手游暑期全新内容“...",
    "needRichText": 1,
    "img": [{ "url": "https://image.duoyi.com/com/322/pic/978e1193971e476c930113453b7b2935.jpg", "width": 567, "height": 384 },
    { "url": "https://image.duoyi.com/com/322/pic/a813d689f38b4b239ddcb6f6763661e6.jpg", "width": 567, "height": 384 },
    { "url": "https://image.duoyi.com/com/322/pic/6df087de4a554ffc9f2d1f1018f7a753.jpg", "width": 567, "height": 384 }],
    "gameName": "神武4手游",
    "time": "2019-07-03",
    "gameIcon": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1582011742167&di=a1fbe78b2b60f0afe89cb66b7175164b&imgtype=jpg&src=http%3A%2F%2Fimg0.imgtn.bdimg.com%2Fit%2Fu%3D3460423160%2C2339690649%26fm%3D214%26gp%3D0.jpg",
    "comment": "20",
    "thumbup": "44"
},
{
    "id": "5",
    "title": "全新内容“星辰化器”宣传片",
    "content": "以天为炉，摘星铸刃！《神武3》手游全新内容“星辰化器”正式上线！全国赛事、120级装备来袭，虚幻入侵2、江湖见闻玩法悉数...",
    "needRichText": 1,
    "img": [{ "url": "https://image.duoyi.com/com/322/pic/dfb15f21f4a846f5b371458700fdd347.jpg", "width": 567, "height": 384 },
    { "url": "https://image.duoyi.com/com/322/pic/ed39518f40bb40dc91ffef23f19275ec.jpg", "width": 567, "height": 384 },
    { "url": "https://image.duoyi.com/com/322/pic/57cd9fdf390e4603bdcf60e010540790.jpg", "width": 567, "height": 384 },
    { "url": "https://image.duoyi.com/com/322/pic/9127399c730e49a2982dc5a2c280aac8.jpg", "width": 567, "height": 384 }],
    "gameName": "神武4手游",
    "time": "2019-07-17",
    "gameIcon": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1582011742167&di=a1fbe78b2b60f0afe89cb66b7175164b&imgtype=jpg&src=http%3A%2F%2Fimg0.imgtn.bdimg.com%2Fit%2Fu%3D3460423160%2C2339690649%26fm%3D214%26gp%3D0.jpg",
    "comment": "4",
    "thumbup": "7"
},
{
    "id": "6",
    "title": "《黄子韬的夏日奇遇》武馆篇首发上...",
    "content": "连续两周，《神武3》暑期合作系列片《黄子韬的夏日奇遇》音乐篇、园林篇相继上线，今日（7月12日），本系列的最终章--武馆...",
    "needRichText": 1,
    "img": [{ "url": "http://olpic.tgbusdata.cn/uploads/allimg/130225/38-130225115123133.jpg", "width": 567, "height": 384 }],
    "gameName": "神武4手游",
    "time": "2019-07-17",
    "gameIcon": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1582011742167&di=a1fbe78b2b60f0afe89cb66b7175164b&imgtype=jpg&src=http%3A%2F%2Fimg0.imgtn.bdimg.com%2Fit%2Fu%3D3460423160%2C2339690649%26fm%3D214%26gp%3D0.jpg",
    "comment": "0",
    "thumbup": "14"
}
]

export default class CommunityVideosView extends React.Component {
    constructor(props) {
        super(props);

        this.canRequest = false

        this.dataArr = new Array();
        dataSource.forEach(dict => {
            var header = JSON.parse(JSON.stringify(dict))
            header.type = 'header'
            this.dataArr.push(header)
            var title = JSON.parse(JSON.stringify(dict))
            title.type = 'title'
            this.dataArr.push(title)
            var content = JSON.parse(JSON.stringify(dict))
            content.type = 'content'
            this.dataArr.push(content)
            var img = JSON.parse(JSON.stringify(dict))
            img.type = 'img'
            this.dataArr.push(img)
            var tool = JSON.parse(JSON.stringify(dict))
            tool.type = 'tool'
            this.dataArr.push(tool)
        });
        // console.log(this.dataArr);

    }

    state = {
        dataList: this.dataArr,
        isRefresh: false,
        isLoading: true,
        page: 1,
        noData: false,
        hasMorePage: true,
        loadingMore: false,
        listHeight: 0,
        listSize: null
    }

    componentDidMount() {
        this.getShowData(1)
    }

    componentWillUnmount() {
        this.timer && clearTimeout(this.timer)
    }

    render() {
        if (this.state.isLoading) {
            return this.renderLoadingView()
        } else if (this.state.noData && !this.state.isLoading) {
            return this.renderEmptyView()
        } else if (!this.state.noData && !this.state.isLoading) {
            return this.renderMainView()
        }
    }

    renderLoadingView() {
        const { style } = this.props
        return (
            <View style={[styles.loading, style]}>
                <ActivityIndicator
                    animating={true}
                    color='gray'
                    size='large'
                />
            </View>
        )
    }

    renderEmptyView() {
        const { style } = this.props
        return (
            <View style={[styles.listEmpty, style]}>
                <Image style={styles.default_img}
                    source={{ uri: 'http://a3.att.hudong.com/68/61/300000839764127060614318218_950.jpg' }} />
                <Text style={styles.default_content}>未获取到数据</Text>
            </View>
        )
    }

    renderMainView() {
        const { style } = this.props
        return (
            <View style={[styles.container, style]}>
                <CommunitySortView style={styles.sortView}
                    dataList={keywords}
                    action={this.selectSortAction}
                />
                <FlatList style={styles.flatList}
                    data={this.state.dataList}
                    keyExtractor={this.keyExtractor}
                    renderItem={this.renderItem}
                    // ItemSeparatorComponent={this.renderSeparator}
                    onScroll={this.onScroll}
                    onScrollBeginDrag={this.onScrollBeginDrag}
                    onScrollEndDrag={this.onScrollEndDrag}
                    onMomentumScrollBegin={this.onMomentumScrollBegin}
                    onMomentumScrollEnd={this.onMomentumScrollEnd}
                    refreshing={this.state.isRefresh}
                    onRefresh={this.onRefresh}
                    onEndReached={this.onEndReached}
                    onEndReachedThreshold={0.1}
                    ListFooterComponent={this.renderFooter}
                    contentContainerStyle={{ flexGrow: 1 }}
                    extraData={this.state}
                />
            </View>
        );
    }

    selectSortAction = (item) => {
        // console.log('选中了分类：' + item)
        // this.getShowData(1,'refresh')
    }

    onEndReached = () => {
        // console.log('onEndReached')
        this.requestMoreData()
    }

    requestMoreData = () => {
        // console.log('requestMoreData')
        if (!this.canRequest) return
        if (this.state.page * dataSource.length < this.state.listSize && !this.state.loadingMore) {
            this.setState({
                loadingMore: true
            }, () => {
                this.getShowData(this.state.page)
            })
        } else if (this.state.page * dataSource.length >= this.state.listSize && !this.state.loadingMore) {
            this.setState({
                hasMorePage: false
            })
        }
    }

    renderFooter = () => {
        if (this.state.hasMorePage && this.state.page >= 1) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator />
                    <Text style={{ marginLeft: 10 }}>正在加载更多数据...</Text>
                </View>
            )
        } else if (!this.state.hasMorePage && this.state.page >= 1) {
            return (
                <View style={{ height: 30, alignItems: 'center', justifyContent: 'flex-start', }}>
                    <Text style={{ color: '#999999', fontSize: 14, marginTop: 5, marginBottom: 5, }}>
                        没有更多数据了
                    </Text>
                </View>
            )
        } else {
            return (
                <View style={styles.footer}>
                    <Text></Text>
                </View>
            )
        }
    }

    onRefresh = () => {
        this.setState({
            isRefresh: true,
            page: 1
        }, () => {
            this.getShowData(1, 'refresh')
        })
    }

    getShowData = (page, type) => {
        this.timer = setTimeout(() => {
            if (type === 'refresh') {
                this.setState({
                    dataList: this.dataArr,
                    page: 1,
                    isRefresh: false,
                    isLoading: false,
                    noData: false,
                    loadingMore: false,
                    hasMorePage: true,
                    listSize: 300
                })
            } else {
                this.setState({
                    dataList: this.dataArr.concat(this.state.dataList),
                    page: this.state.page + 1,
                    isRefresh: false,
                    isLoading: false,
                    noData: false,
                    loadingMore: false,
                    listSize: 300
                })
            }
        }, 50)
    }

    // 此函数用于为给定的item生成一个不重复的key
    keyExtractor = (item, index) => '' + index;

    renderItem = ({ item }) => {
        if (item == null) return
        if (item.type == 'header') {
            return (
                <CommunityHeaderCell data={item} moreAction={this.moreAction} clickCellAction={this.clickCellAction} />
            )
        } else if (item.type == 'title') {
            return (
                <CommunityTitleCell data={item} clickCellAction={this.clickCellAction} />
            )
        } else if (item.type == 'content') {
            return (
                <CommunityContentCell data={item} clickCellAction={this.clickCellAction} />
            )
        } else if (item.type == 'img' && item.img.length == 1) {
            return (
                <CommunityMediaCell data={item} clickImgAction={this.clickImgAction} />
            )
        } else if (item.type == 'img' && item.img.length > 1) {
            return (
                <CommunityMediaGatherCell data={item} clickImgAction={this.clickImgAction} />
            )
        } else if (item.type == 'tool') {
            return (
                <CommunityToolCell data={item} thumbupAction={this.thumbupAction} shareAction={this.shareAction} commentAction={this.commentAction} />
            )
        }
    }

    clickImgAction = (item, imgs, radius, idx) => {
        // console.log('videos_moreAction')
        videos_clickImgAction(item, imgs, radius, idx)
    }

    moreAction = (item) => {
        // console.log('videos_moreAction')
        videos_moreAction(item)
    }

    clickCellAction = (item) => {
        // console.log('videos_clickCellAction')
        videos_clickCellAction(item)
    }

    shareAction = (item) => {
        // console.log('videos_shareAction')
        videos_shareAction(item)
    }

    commentAction = (item) => {
        // console.log('videos_commentAction')
        videos_commentAction(item)
    }

    thumbupAction = (item) => {

    }

    onScroll = (event) => {
        let offSetY = event.nativeEvent.contentOffset.y
        let contentSizeHeight = event.nativeEvent.contentSize.height
        if (contentSizeHeight - offSetY < 2000) {
            this.requestMoreData()
        }
    }

    onScrollBeginDrag = () => {
        // console.log('onScrollBeginDrag');
        this.canRequest = true;
    }
    onScrollEndDrag = () => {
        // console.log('onScrollEndDrag');
        this.canRequest = false;
    }
    onMomentumScrollBegin = () => {
        // console.log('onMomentumScrollBegin');
        this.canRequest = true;
    }
    onMomentumScrollEnd = () => {
        // console.log('onMomentumScrollEnd');
        this.canRequest = false;
    }
}

const styles = StyleSheet.create({
    safeAreaView: {
        flex: 1
    },
    container: {
        flex: 1,
    },
    sortView: {
        height: 50,
        marginLeft: 0,
        marginRight: 0,
    },
    flatList: {

    },
    separator: {
        height: 0.5,
        marginRight: 0,
        backgroundColor: '#ced0ce',
        marginLeft: 10,
    },
    footer: {
        flexDirection: 'row',
        height: 24,
        justifyContent: 'center',
        alignItems: 'center',
        marginBottom: 10,
    },
    loading: {
        justifyContent: 'center',
        alignItems: 'center',
        flex: 1,
    },
    listEmpty: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    default_img: {
        width: 90,
        height: 90,
        marginBottom: 20,
        backgroundColor: '#eeeeee'
    },
    default_content: {
        fontFamily: 'PingFangSC-Regular',
        fontSize: 15,
        height: 21,
        color: '#CCCCCC',
        textAlign: 'center'
    }
})